package com.cloudcc.ccTool;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author T.han
 * @date 2023/8/17 15:09
 * @project CloudccNewPro
 * @Description //TODO
 */
public class CCService {
	public UserInfo userInfo;
	public String ACCESSTOKEN;
	public String path;
	public String URL;

	protected Map<String,Object> record_new;
	protected Map<String,Object> record_old;
	public ServiceResult trigger = new ServiceResult();
	public String objectApiName;
	ResourceBundle prb = PropertyResourceBundle.getBundle("application");// 获取配置文件;
	public String USERNAME=prb.getString("username");
	String orgId = prb.getString("orgId");
	String gatewayUrl = prb.getString("gatewayUrl");

	Logger logger = LoggerFactory.getLogger(this.getClass());

	public CCService(UserInfo userInfo) {
		this.URL = getOrgApiUrl();
		this.ACCESSTOKEN = getToken();
		this.userInfo = userInfo;

	}
	public String gatewayUrl() {
		return gatewayUrl;
	}

	/**
	 * @return java.lang.String
	 * @Description //TODO 获取公有云api网关地址
	 * @Author T.han
	 * @Date 2023/8/17 15:48
	 * @Param
	 **/
	public String getOrgApiUrl() {
		String apiUrl = "";
		String url = prb.getString("url");
		if("".equals(url)){
			String parUrl = "https://developer.apis.cloudcc.cn/oauth/apidomain?scope=cloudccCRM&orgId=" + orgId;
			String relStr = sendGet(parUrl);
			JSONObject relObj = new JSONObject();
			relObj = JSONObject.parseObject(relStr);
			String result = relObj.getString("result");
			if ("true".equals(result)) {
				apiUrl = relObj.getString("orgapi_address");
			}
		}else {
			apiUrl=url;
		}

		return apiUrl;
	}


	/**
	 * @return java.lang.String
	 * @Description //TODO 获取token
	 * @Author T.han
	 * @Date 2023/8/17 16:10
	 * @Param
	 **/
	public String getToken() {
		String accessToken = "";
		String username = prb.getString("username");
		String safetyMark = prb.getString("safetyMark");
		String clientId = prb.getString("clientId");
		String secretKey = prb.getString("secretKey");
		String grant_type = prb.getString("grant_type");
		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
		parObj.put("username", username);
		parObj.put("safetyMark", safetyMark);
		parObj.put("clientId", clientId);
		parObj.put("secretKey", secretKey);
		parObj.put("orgId", orgId);
		parObj.put("grant_type", grant_type);
		path= URL+ "/api/cauth/token";
		if (!"".equals(path)) {
			String relStr = sendPost(path, parObj.toString());
			JSONObject relObj = new JSONObject();
			relObj = JSONObject.parseObject(relStr);
			boolean result = relObj.getBoolean("result");
			if (result) {
				JSONObject data = (JSONObject)relObj.get("data");
				if (data != null && data.containsKey("accessToken")) {
					accessToken = relObj.getJSONObject("data").getString("accessToken");
				} else {
					logger.error("CCService.getToken报错：未获取到accessToken");
				}
			} else {
				String returnInfo = relObj.getString("returnInfo");
				logger.error("CCService.getToken报错：" + returnInfo);
			}
		} else {
			logger.error("CCService.getToken报错：未获取到网关地址");
		}
		return accessToken;
	}

	/**
	 * @return java.util.List<com.cloudcc.newxm.util.CCObject>
	 * @Description //TODO  cquery 查询不加条件
	 * @Author T.han
	 * @Date 2023/8/17 16:38
	 * @Param apiName  对象名
	 **/
	public List<CCObject> cquery(String apiName) {
		List<CCObject> orst = new ArrayList<CCObject>();
		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
		parObj.put("serviceName", "cquery"); //服务名
		parObj.put("objectApiName", apiName); //对象名
		parObj.put("expressions", "1=1"); //查询条件
		parObj.put("isAddDelete", "false"); //是否包含删除数据  true:包含   false:不包含
		parObj.put("fields", "");//查询字段  不填写时sql按 * 返回
		path = URL + "/openApi/common";
		String relStr = CCPost(path, parObj.toString());
		JSONObject relObj = new JSONObject();
		relObj = JSONObject.parseObject(relStr);
		String result = relObj.getString("result");
		String data = relObj.getString("data");
		if ("true".equals(result)&& data!=null) {
			List<Map> rst = relObj.getJSONArray("data").toJavaList(Map.class);
			for (Map m : rst) {
				CCObject co = new CCObject(apiName);
				for (Object _key : m.keySet()) {
					String key = (String) _key;
					co.put(key, m.get(key));
				}
				orst.add(co);
			}
		}
		return orst;
	}

	/**
	 * 根据字段条件查询CCObject对象列表。
	 *
	 * 通过调用开放平台接口，根据提供的apiName、expression和fields参数进行查询。
	 * 查询结果将转换为CCObject对象列表返回。
	 *
	 * @param apiName 对象API名称，用于指定查询的对象。
	 * @param expression 查询表达式，用于指定查询条件。
	 * @param fields 查询字段，用于指定返回字段列表。
	 * @return 返回查询结果的CCObject对象列表。如果没有查询结果或查询失败，返回空列表。
	 */
	public List<CCObject> cqueryByFields(String apiName, String expression, String fields) {
		// 初始化结果列表
		List<CCObject> orst = new ArrayList<CCObject>();
		// 构建请求参数对象
		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
		parObj.put("serviceName", "cquery"); //服务名
		parObj.put("objectApiName", apiName); //对象名
		parObj.put("expressions", expression); //查询条件
		parObj.put("isAddDelete", "false"); //是否包含删除数据  true:包含   false:不包含
		parObj.put("fields", fields);//查询字段  不填写时sql按 * 返回
		// 设置接口路径
		path = URL + "/openApi/common";
		// 发送请求并获取响应
		String relStr = CCPost(path, parObj.toString());
		JSONObject relObj = new JSONObject();
		relObj = JSONObject.parseObject(relStr);
		// 检查查询结果是否成功
		String result = relObj.getString("result");
		String data = relObj.getString("data");
		if ("true".equals(result) && data != null) {
			// 将响应数据转换为List<Map>格式
			List<Map> rst = relObj.getJSONArray("data").toJavaList(Map.class);
			// 遍历每个查询结果项，转换为CCObject对象，并添加到结果列表中
			for (Map m : rst) {
				CCObject co = new CCObject(apiName);
				for (Object _key : m.keySet()) {
					String key = (String) _key;
					co.put(key, m.get(key));
				}
				orst.add(co);
			}
		}
		return orst;
	}






	/**
	 * @return java.util.List<com.cloudcc.newxm.util.CCObject>
	 * @Description //TODO cquery 查询方法
	 * @Author T.han
	 * @Date 2023/8/17 16:42
	 * @Param apiName 对象名
	 * @Param expression  查询条件
	 **/
	public List<CCObject> cquery(String apiName, String expression) {
		List<CCObject> orst = new ArrayList<CCObject>();
		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
		parObj.put("serviceName", "cquery"); //服务名
		parObj.put("objectApiName", apiName); //对象名
		parObj.put("expressions", expression); //查询条件
		parObj.put("isAddDelete", "false"); //是否包含删除数据  true:包含   false:不包含
		parObj.put("fields", "");//查询字段  不填写时sql按 * 返回
		path = URL + "/openApi/common";
		String relStr = CCPost(path, parObj.toString());
		JSONObject relObj = new JSONObject();
		relObj = JSONObject.parseObject(relStr);
		String result = relObj.getString("result");
		String data = relObj.getString("data");
		if ("true".equals(result)&& data!=null) {
			List<Map> rst = relObj.getJSONArray("data").toJavaList(Map.class);
			for (Map m : rst) {
				CCObject co = new CCObject(apiName);
				for (Object _key : m.keySet()) {
					String key = (String) _key;
					co.put(key, m.get(key));
				}
				orst.add(co);
			}
		}
		return orst;
	}

	/**
	 * @return java.util.List<com.cloudcc.newxm.util.CCObject>
	 * @Description //TODO cqlQuery 查询方法
	 * @Author T.han
	 * @Date 2023/8/17 16:41
	 * @Param apiName  对象名
	 * @Param expression  查询sql
	 **/
	public List<CCObject> cqlQuery(String apiName, String expression) {
		List<CCObject> orst = new ArrayList<CCObject>();
		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
//        parObj.put("serviceName", "cqlQueryWithLogInfo"); //服务名
		parObj.put("serviceName", "cqlQuery"); //服务名
		parObj.put("objectApiName", apiName); //对象名
		parObj.put("expressions", expression); //查询条件
		//拼接接口地址
		path = URL + "/openApi/common";
		String relStr = CCPost(path, parObj.toString());
		JSONObject relObj = new JSONObject();
		relObj = JSONObject.parseObject(relStr);
		String result = relObj.getString("result");
		String data = relObj.getString("data");
		if ("true".equals(result)&& data!=null) {
			List<Map> rst = relObj.getJSONArray("data").toJavaList(Map.class);
			for (Map<String,Object> m : rst) {
				CCObject co = new CCObject(apiName);
				for (Object _key : m.keySet()) {
					String key = (String) _key;
					co.put(key, m.get(key));
				}
				orst.add(co);
			}
		}
		return orst;
	}

	/**
	 * @Author lijun
	 * @Description 查询CC共享数据
	 * @Date 2024/7/3
	 * @Param apiName 对象apiname
	 * @param expression 查询条件
	 * @param isDataObject 传入false查共享数据，传true查正常业务数据
	 * @return java.util.List<com.cloudcc.core.CCObject>
	 **/
	public List<CCObject> cquery(String apiName, String expression, boolean isDataObject) {
		if(isDataObject) {
			return this.cquery(apiName, expression);
		}
//		List<CCObject> shareDataList = new ArrayList<>();
//		return shareDataList;
		List<CCObject> orst = new ArrayList<>();
		path = URL + "/api/openCall/common";
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("className", "CT_CheckDataShareUtils");
		jsonObject.put("methodName", "queryShareData");
		JSONArray methodParams = new JSONArray();
		JSONObject param1 = new JSONObject();
		param1.put("argType", "java.lang.String");
		param1.put("argValue", apiName);
		methodParams.add(param1);
		JSONObject param2 = new JSONObject();
		param2.put("argType", "java.lang.String");
		param2.put("argValue", expression);
		methodParams.add(param2);
		jsonObject.put("params", methodParams);
		String respText = CCPost(path, jsonObject.toJSONString());
		JSONObject relObj = JSONObject.parseObject(respText);
		String result = relObj.getString("result");
		String data = relObj.getString("data");
		if ("true".equals(result)&& data!=null) {
			List<Map> rst = relObj.getJSONArray("data").toJavaList(Map.class);
			for (Map<String,Object> m : rst) {
				CCObject co = new CCObject(apiName);
				for (Object _key : m.keySet()) {
					String key = (String) _key;
					co.put(key, m.get(key));
				}
				orst.add(co);
			}
		}
		return orst;
	}

	/**
	 * @Description //TODO update方法
	 * @Author T.han
	 * @Date 2023/8/18 10:02
	 * @Param cobj
	 * @return void
	 **/
	public ServiceResult update(CCObject cobj) {
		JSONArray arry = new JSONArray();
		JSONObject obj = new JSONObject();
		String objectApiName = "";
		for (String _key : cobj.keySet()) {
			if ("CCObjectAPI".equals(_key)) {
				objectApiName = cobj.get("CCObjectAPI") == null ? "" : cobj.get("CCObjectAPI") + "";
			} else {
				String values = cobj.get(_key) == null ? "" : cobj.get(_key) + "";
				obj.put(_key, values);
			}
		}
		arry.add(obj);

		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
		parObj.put("serviceName", "update"); //服务名
		parObj.put("objectApiName", objectApiName); //对象名
		parObj.put("data", arry.toString()); //查询条件
		try {
			TriggerInvoker invoker = new TriggerInvoker(userInfo,"update","before");
			invoker.handler(cobj);
			path = URL + "/openApi/common";
			String relStr = CCPost(path, parObj.toString());
			JSONObject relObj = JSONObject.parseObject(relStr);
			boolean result = relObj.getBoolean("result");
			if(result){
				JSONObject outObj = relObj.getJSONObject("data");
				if(outObj.containsKey("ids")){
					JSONArray outData = outObj.getJSONArray("ids");
					StringBuilder sb = new StringBuilder();
					boolean hasSuccess = false; // 用于跟踪是否有成功处理的条目
					for(int i=0;i < outData.size();i++) {
						JSONObject acc = outData.getJSONObject(i);
						if(acc.getBoolean("success")){
							String id = acc.getString("id");
							if (sb.length() > 0) {
								sb.append(',');
							}
							sb.append(id);
							hasSuccess = true;
						}else{
							logger.error("update报错: " + acc.getString("errors"));
						}
					}
					if (hasSuccess) {
						String retIds = sb.toString();
						logger.info("update成功----开始触发update after触发器: " + retIds);
						cobj.put("id",retIds);
						invoker = new TriggerInvoker(userInfo,"update","after");
						invoker.handler(cobj);
					}
				}else{
					logger.error("update未获取到ids 参数");
				}

			}else{
				logger.error("update报错= " + relObj.getString("returnInfo"));
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("update报错= " + e);
		}
		return null;
	}

	/**
	 * @Description //TODO  insert 方法
	 * @Author T.han
	 * @Date 2023/8/18 10:27
	 * @Param cobj 新建 json参数
	 * @return com.cloudcc.newxm.util.ServiceResult  返回新建数据id
	 **/
	public ServiceResult insert(CCObject cobj) {
		ServiceResult sr = new ServiceResult();
		JSONArray arry = new JSONArray();
		JSONObject obj = new JSONObject();
		String objectApiName = "";
		for (String _key : cobj.keySet()) {
			if ("CCObjectAPI".equals(_key)) {
				objectApiName = cobj.get("CCObjectAPI") == null ? "" : cobj.get("CCObjectAPI") + "";
			} else {
				String values = cobj.get(_key) == null ? "" : cobj.get(_key) + "";
				obj.put(_key, values);
			}
		}
//        cobj.remove("CCObjectAPI");
		arry.add(obj);
		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
		parObj.put("serviceName", "insert"); //服务名
		parObj.put("objectApiName", objectApiName); //对象名
		parObj.put("data", arry.toString()); //查询条件
		logger.info("parObj = " + parObj);
		try {
			//执行触发器
			TriggerInvoker invoker = new TriggerInvoker(userInfo,"insert","before");
			invoker.handler(cobj);
			path = URL + "/openApi/common";
			String relStr = CCPost(path, parObj.toString());
			logger.info("insert_relStr = " + relStr);
			JSONObject relObj = JSONObject.parseObject(relStr);

			String result = relObj.getString("result");
			if ("true".equals(result)) {
				JSONArray outData = relObj.getJSONObject("data").getJSONArray("ids");
				StringBuilder sb = new StringBuilder();
				for(int i=0;i < outData.size();i++) {
					JSONObject acc = outData.getJSONObject(i);
					if(acc.getBoolean("success")){
						String id = acc.getString("id");
						if (sb.length() > 0) {
							sb.append(',');
						}
						sb.append(id);
					}else{
						logger.error("insert报错: " + acc.getString("errors"));
					}
				}
				String retIds = sb.toString();
				sr.put("id",retIds);
				cobj.put("id",retIds);
				invoker = new TriggerInvoker(userInfo,"insert","after");
				invoker.handler(cobj);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("insert报错= " + e);
		}
		System.out.println("sr = " + sr);
		return sr;
	}

	public ServiceResult insert(List<CCObject> datalist) {
		// TODO Auto-generated method stub
		ServiceResult sr = new ServiceResult();
		JSONArray arry = new JSONArray();

		String objectApiName = "";

		for (CCObject cobj : datalist) {
			JSONObject obj = new JSONObject();
			for (String _key : cobj.keySet()) {
				if ("CCObjectAPI".equals(_key)) {
					objectApiName = cobj.get("CCObjectAPI") == null ? "" : cobj.get("CCObjectAPI") + "";
				} else {
					String values = cobj.get(_key) == null ? "" : cobj.get(_key) + "";
					obj.put(_key, values);
				}
			}
			arry.add(obj);
		}

		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
		parObj.put("serviceName", "insert"); //服务名
		parObj.put("objectApiName", objectApiName); //对象名
		parObj.put("data", arry.toString()); //查询条件
		System.out.println("parObj = " + parObj);
		try {
			path = URL + "/openApi/common";
			String relStr = CCPost(path, parObj.toString());
			logger.info("insert_relStr = " + relStr);
			JSONObject relObj = new JSONObject();
			relObj = JSONObject.parseObject(relStr);
			String result = relObj.getString("result");
			if ("true".equals(result)) {
				JSONArray outData = relObj.getJSONObject("data").getJSONArray("ids");
				StringBuilder sb = new StringBuilder();
				for(int i=0;i < outData.size();i++) {
					JSONObject acc = outData.getJSONObject(i);
					if(acc.getBoolean("success")){
						String id = acc.getString("id");
						if (sb.length() > 0) {
							sb.append(',');
						}
						sb.append(id);
					}else{
						logger.error("insert报错: " + acc.getString("errors"));
					}
				}
				String retIds = sb.toString();
				sr.put("id",retIds);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("insert报错= " + e);
		}
		System.out.println("sr = " + sr);
		return sr;
	}


	public ServiceResult update(List<CCObject> datalist) {
		// TODO Auto-generated method stub
		ServiceResult sr = new ServiceResult();
		JSONArray arry = new JSONArray();
		String objectApiName = "";

		for (CCObject cobj : datalist) {
			JSONObject obj = new JSONObject();
			for (String _key : cobj.keySet()) {
				if ("CCObjectAPI".equals(_key)) {
					objectApiName = cobj.get("CCObjectAPI") == null ? "" : cobj.get("CCObjectAPI") + "";
				} else {
					String values = cobj.get(_key) == null ? "" : cobj.get(_key) + "";
					obj.put(_key, values);
				}
			}
			arry.add(obj);
		}
		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
		parObj.put("serviceName", "update"); //服务名
		parObj.put("objectApiName", objectApiName); //对象名
		parObj.put("data", arry.toString()); //查询条件
//        System.out.println("parObj = " + parObj);
		try {
			path = URL + "/openApi/common";
			String relStr = CCPost(path, parObj.toString());
			logger.info("update_relStr = " + relStr);
			JSONObject relObj = new JSONObject();
			relObj = JSONObject.parseObject(relStr);
			String result = relObj.getString("result");
			if ("true".equals(result)) {
				JSONArray outData = relObj.getJSONObject("data").getJSONArray("ids");
				StringBuilder sb = new StringBuilder();
				for(int i=0;i < outData.size();i++) {
					JSONObject acc = outData.getJSONObject(i);
					if(acc.getBoolean("success")){
						String id = acc.getString("id");
						if (sb.length() > 0) {
							sb.append(',');
						}
						sb.append(id);
					}else{
						logger.error("update报错: " + acc.getString("errors"));
					}
				}
				String retIds = sb.toString();
				sr.put("id",retIds);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("update报错= " + e);
		}
		System.out.println("sr = " + sr);
		return sr;
	}
	/**
	 * @Description //TODO 删除方法
	 * @Author T.han
	 * @Date 2023/8/18 10:38
	 * @Param cobj 参数数据 {“id”:"a1231111"}
	 * @return void
	 **/
	public void delete(CCObject cobj) {
		JSONArray arry = new JSONArray();
		JSONObject obj = new JSONObject();
		String objectApiName = "";
		for (String _key : cobj.keySet()) {
			if ("CCObjectAPI".equals(_key)) {
				objectApiName = cobj.get("CCObjectAPI") == null ? "" : cobj.get("CCObjectAPI") + "";
			} else {
				String values = cobj.get(_key) == null ? "" : cobj.get(_key) + "";
				obj.put(_key, values);
			}
		}
		arry.add(obj);
		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
		parObj.put("serviceName", "delete"); //服务名
		parObj.put("objectApiName", objectApiName); //对象名
		parObj.put("data", arry.toString()); //查询条件
		System.out.println("parObj = " + parObj);
		try {
			TriggerInvoker invoker = new TriggerInvoker(userInfo,"delete","before");
			invoker.handler(cobj);
			path = URL + "/openApi/common";
			String relStr = CCPost(path, parObj.toString());
			invoker = new TriggerInvoker(userInfo,"delete","after");
			invoker.handler(cobj);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("delete报错= " + e);
		}
	}


	/**
	 * 删除数据列表中的对象。
	 * 该方法通过构建一个包含删除信息的JSON对象，然后发送HTTP请求到指定的API来实现删除操作。
	 * @param datalist 待删除的对象列表，每个对象是一个CCObject的实例。
	 */
	public void delete(List<CCObject> datalist) {
		// 初始化一个JSONArray用于存储待删除的对象细节
		JSONArray arry = new JSONArray();
		// 初始化一个JSONObject用于存储单个对象的细节
		JSONObject obj = new JSONObject();
		// 用于存储CCObjectAPI的名称
		String objectApiName = "";

		// 遍历对象列表，填充JSONObject
		for (CCObject cobj : datalist) {
			for (String _key : cobj.keySet()) {
				if ("CCObjectAPI".equals(_key)) {
					// 如果键是CCObjectAPI，获取其值（如果存在）并存储
					objectApiName = cobj.get("CCObjectAPI") == null ? "" : cobj.get("CCObjectAPI") + "";
				} else {
					// 对于其他键，获取其值（如果存在）并添加到JSONObject中
					String values = cobj.get(_key) == null ? "" : cobj.get(_key) + "";
					obj.put(_key, values);
				}
			}
			// 将单个对象的JSONObject添加到数组中
			arry.add(obj);
			// 重置单个对象的JSONObject，为下一个对象的处理做准备
			obj = new JSONObject();
		}

		// 初始化参数对象JSONObject，用于构造API请求
		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
		// 设置服务名
		parObj.put("serviceName", "delete"); //服务名
		// 设置对象名
		parObj.put("objectApiName", objectApiName); //对象名
		// 设置数据部分
		parObj.put("data", arry.toString()); //查询条件

		// 发送HTTP POST请求到指定URL，执行删除操作
		try {
			path = URL + "/openApi/common";
			String relStr = CCPost(path, parObj.toString());
			// 记录删除操作的结果
			logger.info("update_relStr = " + relStr);
			JSONObject relObj = new JSONObject();
			relObj = JSONObject.parseObject(relStr);
			// 检查删除操作是否成功
			String result = relObj.getString("result");
			if ("true".equals(result)) {
				// 如果成功，处理返回的删除的ID列表
				JSONArray outData = relObj.getJSONObject("data").getJSONArray("ids");
				StringBuilder sb = new StringBuilder();
				for(int i=0;i < outData.size();i++) {
					JSONObject acc = outData.getJSONObject(i);
					if(acc.getBoolean("success")){
						// 如果单个删除操作成功，追加ID到字符串中
						String id = acc.getString("id");
						if (sb.length() > 0) {
							sb.append(',');
						}
						sb.append(id);
					}else{
						// 如果单个删除操作失败，记录错误信息
						logger.error("delete报错: " + acc.getString("errors"));
					}
				}
			}
		} catch (Exception e) {
			// 记录任何在删除过程中发生的异常
			e.printStackTrace();
			logger.error("delete报错= " + e);
		}
	}



	public ServiceResult upsert(CCObject cobj) {
		ServiceResult sr = new ServiceResult();
		JSONArray arry = new JSONArray();
		JSONObject obj = new JSONObject();
		String objectApiName = "";
		for (String _key : cobj.keySet()) {
			if ("CCObjectAPI".equals(_key)) {
				objectApiName = cobj.get("CCObjectAPI") == null ? "" : cobj.get("CCObjectAPI") + "";
			} else {
				String values = cobj.get(_key) == null ? "" : cobj.get(_key) + "";
				obj.put(_key, values);
			}
		}
		arry.add(obj);
		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
		parObj.put("serviceName", "upsert"); //服务名
		parObj.put("objectApiName", objectApiName); //对象名
		parObj.put("data", arry.toString()); //查询条件

		try {
			TriggerInvoker invoker = new TriggerInvoker(userInfo,"upsert","before");
			invoker.handler(cobj);
			path = URL + "/openApi/common";
			String relStr = CCPost(path, parObj.toString());
			JSONObject relObj = new JSONObject();
			relObj = JSONObject.parseObject(relStr);
			String result = relObj.getString("result");
			if ("true".equals(result)) {
				JSONArray outData = relObj.getJSONObject("data").getJSONArray("ids");
				JSONObject acc = outData.getJSONObject(0);
				if(acc.getBoolean("success")){
					sr.put("id",acc.getString("id"));
					cobj.put("id",acc.getString("id"));
				}
				invoker = new TriggerInvoker(userInfo,"upsert","before");
				invoker.handler(cobj);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("upsert报错= " + e);
		}
		return sr;
	}


	public List<Map> getPicklistValue(String tableName, String fieldApi, String recordType)
			throws Exception {
		// 初始化一个用于存储下拉列表值的集合
		List<Map> PickListValue = new ArrayList<>();
		// 准备请求参数
		JSONObject parJson = new JSONObject();
		parJson.put("objectApiName", tableName);
		parJson.put("fieldApi", fieldApi);
		parJson.put("recordType", recordType);

		// 定义请求路径和服务名称
		String serviceName = "getPickListValue";
		// 构建请求体
		JSONObject requestBody = new JSONObject();
		requestBody.put("serviceName", serviceName);
		requestBody.put("data", parJson.toJSONString());
		try {
			// 发起请求，并处理返回结果
			path = URL + "/openApi/common";
			String operationResult = CCPost(path, requestBody.toString());
			JSONObject rstData = JSONObject.parseObject(operationResult);
			String result = rstData.getString("result");
			if ("true".equals(result)) {
				// 处理返回的数据，提取有效下拉列表值
				if (rstData.containsKey("data")) {
					PickListValue = rstData.getJSONArray("data").toJavaList(Map.class);
				}
			} else {
				// 如果结果不成功，则抛出异常
				throw new Exception(rstData.getString("returnInfo"));

			}
		} catch (Exception e) {
			// 异常处理逻辑尚未实现
		}
		return PickListValue;
	}

	public ServiceResult createUser(String loginName, String name, String email, String profileId, String roleId, String password) {
		ServiceResult sr = new ServiceResult();
		JSONArray arry = new JSONArray();
		JSONObject obj = new JSONObject();
		//拼接 parObj 参数
		JSONObject parObj = new JSONObject();
		parObj.put("serviceName", "createUser"); //服务名
		parObj.put("loginName", loginName); //
		parObj.put("name", name); //
		parObj.put("email", email); //
		parObj.put("profileId", profileId); //
		parObj.put("roleId", roleId); //
		parObj.put("password", password); //
		parObj.put("sendEmail", "0"); //

		try {
			path = URL + "/openApi/common";
			String relStr = CCPost(path, parObj.toString());
			logger.info("createUser-relStr = " + relStr);
			JSONObject relObj = new JSONObject();
			relObj = JSONObject.parseObject(relStr);
			String result = relObj.getString("result");

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("createUser= " + e);
		}
		return sr;
	}



	/**
	 * @Description //TODO post请求
	 * @Author T.han
	 * @Date 2023/8/18 10:03
	 * @Param path  接口地址 http://127.0.0.1/cloudcc/outken
	 * @Param param 参数 json
	 * @Param IsToken headers是否添加token  false：不添加   true:添加
	 * @return java.lang.String
	 **/
	public String sendPost(String path, String param) {
		OutputStreamWriter out = null;
		BufferedReader br = null;
		StringBuffer sb = new StringBuffer();
		String exception = "";
		String result = "";
		try {
			URL url = new URL(path);
			HttpURLConnection conn = null;
			// 打开和URL之间的连接
			conn = (HttpURLConnection) url.openConnection();
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");    // POST方法
			conn.setConnectTimeout(15 * 1000);// 设置连接超时时间为5秒
			conn.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒
			String tokens = "";
			// 设置通用的请求属性
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("accept", "*/*");
			conn.connect();
			// 获取URLConnection对象对应的输出流
			out = new OutputStreamWriter(conn.getOutputStream());
			// 发送请求参数
			BufferedWriter bw = new BufferedWriter(out);
			bw.write(param);
			// flush输出流的缓冲
			bw.flush();
			// 定义BufferedReader输入流来读取URL的响应
			br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			exception = "发送 POST 请求出现异常！" + e;
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (br != null) {
					br.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		if (sb.toString().isEmpty()) {
			result = exception;
		} else {
			result = sb.toString();
		}
		return result;
	}

	public String CCPost(String path, String param) {

		OutputStreamWriter out = null;
		BufferedReader br = null;
		StringBuffer sb = new StringBuffer();
		String exception = "";
		String result = "";
		try {
			URL url = new URL(path);
			HttpURLConnection conn = null;
			// 打开和URL之间的连接
			conn = (HttpURLConnection) url.openConnection();
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");    // POST方法
			conn.setConnectTimeout(15 * 1000);// 设置连接超时时间为5秒
			conn.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒
			String tokens = "";
			// 设置通用的请求属性
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("accessToken", ACCESSTOKEN);
			conn.connect();
			// 获取URLConnection对象对应的输出流
			out = new OutputStreamWriter(conn.getOutputStream());
			// 发送请求参数
			BufferedWriter bw = new BufferedWriter(out);
			bw.write(param);
			// flush输出流的缓冲
			bw.flush();
			// 定义BufferedReader输入流来读取URL的响应
			br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			exception = "发送 POST 请求出现异常！" + e;
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (br != null) {
					br.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		if (sb.toString().isEmpty()) {
			result = exception;
		} else {
			result = sb.toString();
		}
		return result;
	}

	/**
	 * @Description //TODO GET请求方法
	 * @Author T.han
	 * @Date 2023/8/18 10:06
	 * @Param path 地址   http://127.0.0.1/cloudcc/outoken?key1=value1&key2=value2
	 * @return java.lang.String
	 **/
	public static String sendGet(String path) {
		StringBuffer sb = new StringBuffer();
		String exception = "";
		String result = "";
		try {
			URL url = new URL(path);
			InputStream is = url.openStream();
			InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
			BufferedReader br = new BufferedReader(isr);
			String line;//读取数据
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			br.close();
			isr.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
			exception = "发送 GET 请求出现异常！" + e;
		}
		if (sb.toString().isEmpty()) {
			result = exception;
		} else {
			result = sb.toString();
		}
		return result;
	}

	/**
	 * 获取自定义列表设置
	 * @param api 接口名称，用于指定获取哪个接口的自定义设置
	 * @return 返回一个包含自定义设置数据的Map对象
	 */
	public Map<String,Object> getListCustomSetting(String api) {
		// 初始化数据映射对象，用于存放最终返回的数据
		Map<String,Object> datMap = new HashMap<String,Object>();
		// 创建参数数组，用于存放调用接口的参数
		JSONArray argArray	= new JSONArray();
		JSONObject arryStr = new JSONObject();
		arryStr.put("argType", String.class);
		arryStr.put("argValue", api);
		argArray.add(arryStr);
		JSONObject parObj = new JSONObject();
		parObj.put("className", "TCCCustomSetting"); //服务名
		parObj.put("methodName", "getListCustomSetting"); //方法名
		parObj.put("params", argArray); //查询条件
		try {
			path =  URL+ "/api/openCall/common";
			String relStr = CCPost(path, parObj.toString());
			JSONObject relData = JSONObject.parseObject(relStr);
			if (relData.getBoolean("result")) {
				JSONObject data = relData.getJSONObject("data");
				datMap.putAll(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("upsert报错= " + e);
		}

		return datMap;
	}
	/**
	 * 获取自定义设置列表。
	 * 通过调用指定API和键值，来获取相应的自定义设置数据。
	 * @author admin
	 * @Version Created on 2024.4.10
	 * @param api 要调用的API名称。
	 * @param key 查询设置列表时使用的键值。
	 * @return 返回一个包含自定义设置数据的Map对象。如果发生错误，可能返回空或错误信息的Map。
	 */
	public Map<String,Object> getListCustomSetting(String api, String key) {
		Map<String,Object> datMap = new HashMap<String,Object>();
		JSONArray argArray	= new JSONArray();

		JSONObject apiParam = new JSONObject();
		apiParam.put("argType", String.class);
		apiParam.put("argValue", api);
		argArray.add(apiParam);

		JSONObject keyParam = new JSONObject();
		keyParam.put("argType", String.class);
		keyParam.put("argValue", key);
		argArray.add(keyParam);
		path =  URL+ "/api/openCall/common";
		JSONObject parObj = new JSONObject();
		parObj.put("className", "TCCCustomSetting"); //服务名
		parObj.put("methodName", "getListCustomSetting"); //方法名
		parObj.put("params", argArray); //查询条件

		try {
			String relStr = CCPost(path, parObj.toString());
			JSONObject relData = JSONObject.parseObject(relStr);
			if (relData.getBoolean("result")) {
				JSONObject data = relData.getJSONObject("data");
				datMap.putAll(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("upsert报错= " + e);
		}

		return datMap;
	}

	/**
	 * 获取自定义设置列表。
	 * 查询“层次结构”类型的自定义设置数据,返回对应apiName和权限（id为简档id或用户id）的单条数据
	 * @author admin
	 * @Version Created on 2024.4.10
	 * @param api 要调用的API名称。
	 * @param id id为简档id或用户id。
	 * @return 返回一个包含自定义设置数据的Map对象。如果发生错误，可能返回空或错误信息的Map。
	 */
	public Map<String,Object> getCustomSetting(String api, String id) {
		Map<String,Object> datMap = new HashMap<String,Object>();
		JSONArray argArray	= new JSONArray();

		JSONObject apiParam = new JSONObject();
		apiParam.put("argType", String.class);
		apiParam.put("argValue", api);
		argArray.add(apiParam);

		JSONObject keyParam = new JSONObject();
		keyParam.put("argType", String.class);
		keyParam.put("argValue", id);
		argArray.add(keyParam);

		JSONObject parObj = new JSONObject();
		parObj.put("className", "TCCCustomSetting"); //服务名
		parObj.put("methodName", "getCustomSetting"); //方法名
		parObj.put("params", argArray); //查询条件

		try {
			path =  URL+ "/api/openCall/common";
			String relStr = CCPost(path, parObj.toString());
			JSONObject relData = JSONObject.parseObject(relStr);
			if (relData.getBoolean("result")) {
				JSONObject data = relData.getJSONObject("data");
				datMap.putAll(data);
			}
			//ObjectMapper objectMapper = new ObjectMapper();
			// 将对象描述转换为字符串并添加到结果中
			//datMap = objectMapper.convertValue(objectMapper, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("upsert报错= " + e);
		}

		return datMap;
	}

	public Map cqueryForEs(String account, String where, String aTrue, String s) {
		return null;
	}

	public String getPermission(String service_record, String id, String edit) {
		return null;
	}

	public List<CCObject> cqueryWithRoleRight(String service_record, String s) {
		return  null;
	}

	public ServiceResult insert(CCObject reminder, boolean b, boolean b1, boolean b2, boolean b3) {
		return null;
	}

	public void addCaseTeam(List<Map> caseteamList, String recordid) {
	}

	public ServiceResult update(CCObject serv, boolean b, boolean b1, boolean b2, boolean b3) {
		return null;
	}
	public ServiceResult insertLt(CCObject in) throws Exception {
		// TODO Auto-generated method stub
		List<CCObject> datalist = new ArrayList<CCObject>();
		datalist.add(in);
		insert(datalist);
		return null;
	}

	public ServiceResult updateLt(CCObject objectData) throws Exception  {
		// TODO Auto-generated method stub
		//不执行触发器
		List<CCObject> datalist = new ArrayList<CCObject>();
		datalist.add(objectData);
		update(datalist);
		return null;
	}

	public void addMicroPost(String string, Object object, Object object2, Object object3, Object object4,
							 Object object5, Object object6, String string2, String emailSubject, String string3, String stkhid,
							 String stkhid2) {
		// TODO Auto-generated method stub

	}

	public String sendEmail(String subject, String htmlBody, String toAddress, String relatedid, String ccaddress, String bccaddress, String attachmentId, String s, String s1) {
		return "";
	}

	public String uploadAttachment(Map m){
		return null;
	}

	public void deleteShareObjectBySql(String account, String s) {

	}

	/**
	 * 提交审批请求
	 * @param id 相关ID，用于构建审批请求的数据
	 * @param s 未使用的参数
	 * @param s1 未使用的参数
	 * @return 返回操作结果，成功则返回"提交成功"，失败则返回错误信息
	 */
	public String submitForApproval(String id, String s, String s1) {
		logger.info("submitForApproval开始");
		// 输入验证，避免空值或空白字符串
		if (id == null || id.trim().isEmpty()) {
			logger.error("submitForApproval异常：Invalid input parameters.");
			return "Invalid input parameters.";
		}
		JSONObject obj = new JSONObject();
		obj.put("relateId", id);
		JSONObject requestBody = new JSONObject();
		// 构建请求体，包含服务名称、对象API名称和要删除的数据
		requestBody.put("serviceName", "submitForApproval");
		requestBody.put("data", obj);
		String operationResult="";
		logger.info("提交审批请求-参数："+requestBody.toString());
		try {
			path = URL + "/openApi/common";
			// 执行删除操作，并获取操作结果
			operationResult = CCPost(path, requestBody.toString());
			logger.info("提交审批请求-结果："+operationResult);
			JSONObject rstData = JSONObject.parseObject(operationResult);
			if (rstData.getBoolean("result")) {
				// 如果结果为true，则返回操作结果
				logger.info("提交成功");
				return "提交成功";
			}
		} catch (Exception e) {
			// 捕获异常，将异常信息作为操作结果返回
			operationResult = e.getMessage();
			logger.error("数据"+id+"提交审批异常："+operationResult);
		}
		return operationResult;
	}

	public String process(String processType, String tid, String touserId, String comments, String appPath) {
		return null;
	}

	/* *
	 * @Description:  cs.getObjectRight查询对象的权限 返回值中包含了
	 * 查看、新建、修改、删除、查看全部、修改全部的权限(值对应此顺序)，如果有权限则对应的值为1，无权限为0。
	 * @author: jarry
	 * @date: 2024/4/28 11:55
	 * @param objectApiName: 对象名称
	 */
	public String getObjectRight(String apiName){
		return "1,1,1,1,1,1";
	}

	/**
	 * 查询附件
	 * @param fjid
	 * @return
	 */
	public List<Map> queryRemarkAndAttachs(String fjid){
		return null;
	}

}
